package indoor.nexd.com.nexdmap.presenter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.litesuits.orm.db.DataBase;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import indoor.nexd.com.nexdmap.R;
import indoor.nexd.com.nexdmap.application.MyApplication;
import indoor.nexd.com.nexdmap.model.Mallconfig;
import indoor.nexd.com.nexdmap.model.MallModel;
import indoor.nexd.com.nexdmap.ui.inte.ISignInActivity;
import indoor.nexd.com.nexdmap.util.CheckWifiisAvailable;
import indoor.nexd.com.nexdmap.util.MD5Util;
import indoor.nexd.com.nexdmap.util.OkHttpClientManager;
import indoor.nexd.com.nexdmap.util.UrlUtil;

/**
 * 用户登录业务处理类
 * <p/>
 * Created by xun on 2016/3/16.
 */

public class SignInPresenter extends BasePresenter<ISignInActivity> {
    private int loginCode = SUCCESS_VALIDATE;
    public static final int SUCCESS_VALIDATE = 0;
    public static final int ERROR_PWD = 1;
    public static final int ERROR_EMAIL_EMPTY = 2;
    public static final int ERROR_EMAIL_VALIDATE = 3;
    public int failedCount = 0;
    public static final int ERROR_LOGIN_COUNT_LESS = 1;
    private DataBase dbOrm;

    public SignInPresenter(Context context, ISignInActivity iSignInActivity) {
        super(context, iSignInActivity);
        this.dbOrm = MyApplication.getLiteOrm();
        Log.i("mallInfo",dbOrm+"");
    }


    public int validateMsg(String username, String pwd) {
        boolean cancel = false;
        if (TextUtils.isEmpty(pwd) || pwd.length() <= 4) {
            loginCode = ERROR_PWD;
            cancel = true;
        }
        if (TextUtils.isEmpty(username)) {
            loginCode = ERROR_EMAIL_EMPTY;
            cancel = true;
        } else if (!username.contains("@")) {
            loginCode = ERROR_EMAIL_VALIDATE;
            cancel = true;
        }
        if (!cancel) {
            loginCode = SUCCESS_VALIDATE;
        }
        return loginCode;
    }

    public void checkOpenWifi() {
        if (!CheckWifiisAvailable.isConnected(context)) {
            showToast("请开启网络！");
        }
    }

    public void doLogin(String username, String pwd) {
        setProgressVisible(View.VISIBLE);
        StringBuilder url = new StringBuilder();
        url.append(UrlUtil.Base_IP)
                .append("demo/v1.0/userLogin.do?appKey=")
                .append(MyApplication.APP_KEY)
                .append("&userName=")
                .append(username)
                .append("&password=")
                .append(MD5Util.parseStrToMd5L32(pwd));
        Log.d("login", url.toString());
        OkHttpClientManager.postAsyn(url.toString(), (OkHttpClientManager.Param[]) null, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                showToast("您的网络状况差，请尝试重新连接！");
                setProgressVisible(View.GONE);
            }

            @Override
            public void onResponse(String response) {
                setProgressVisible(View.GONE);
                Log.d("LogResponse", response);
                if (!TextUtils.isEmpty(response)) {
                    try {
                        final JSONObject resultJson = new JSONObject(response);
                        Log.d("resultJson", resultJson.toString());
                        if (resultJson.getBoolean("isSuccess")) {
                            // 获取配置项,并初始化配置列表
                            JSONObject configJson = resultJson.getJSONObject("config");
                            MyApplication.IS_WIFI = configJson.getBoolean("wifi");
                            MyApplication.IS_MAP = configJson.getBoolean("map");
                            MyApplication.IS_BEACON = configJson.getBoolean("bluetooth");
                            MyApplication.IS_ROUTE_PLAN = configJson.getBoolean("pathPlan");
                            // 设置下发的userId
                            MyApplication.userId = resultJson.getString("userId");
                            StringBuilder mallUrl = new StringBuilder();
                            mallUrl.append(UrlUtil.Base_IP)
                                    .append("demo/mall/v1.0/queryMallList.do?userId=")
                                    .append(MyApplication.userId)
                                    .append("&appKey=")
                                    .append(MyApplication.APP_KEY);
                            Log.d("requestMallUrl", mallUrl.toString());
                            OkHttpClientManager.postAsyn(mallUrl.toString(), "", new OkHttpClientManager.ResultCallback<String>() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    Log.e("Login", e.getMessage());
                                }

                                @Override
                                public void onResponse(String response) {
                                    Log.d("response", response);
                                    if (!TextUtils.isEmpty(response)) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            if (jsonObject.getBoolean("isSuccess")) {
                                                // 获取该用户支持的商场列表
                                                if (MyApplication.mallList.size() != 0) {
                                                    MyApplication.mallList.clear();
                                                }
                                                JSONArray jsonArray = jsonObject.getJSONArray("malls");
                                                for (int i = 0; i < jsonArray.length(); i++) {
                                                    JSONObject mallJson = jsonArray.getJSONObject(i);
                                                    MallModel mallModel = new MallModel();
                                                    mallModel.setBaiduLat(mallJson.getString("baiduLat"));
                                                    mallModel.setBaiduLng(mallJson.getString("baiduLng"));
                                                    mallModel.setMallCName(mallJson.getString("mallCName"));
                                                    mallModel.setMallEName(mallJson.getString("mallEName"));
                                                    mallModel.setMallId(mallJson.getString("mallId"));
                                                    mallModel.setMd5(mallJson.getString("md5"));
                                                    mallModel.setUrl(mallJson.getString("url"));
                                                    MyApplication.mallList.add(mallModel);
                                                    ArrayList<Mallconfig> mallInfo = dbOrm.query(new QueryBuilder<>(Mallconfig.class)
                                                            .where("mallID=?", new String[]{mallModel.getMallId()})
                                                    );
                                                    if (mallInfo.size() == 0) {
                                                        Log.i("mallInfo", mallModel.toString());
                                                        Mallconfig mallConfig = new Mallconfig();
                                                        mallConfig.setMallID(mallModel.getMallId());
                                                        mallConfig.setMd5(mallModel.getMd5());
                                                        Log.i("mallInfo", mallConfig.toString());
                                                        dbOrm.save(mallConfig);
                                                    }

                                                }
                                                intoNextActivity();
                                            }
                                        } catch (JSONException e) {
                                            showToast(context.getString(R.string.error_json_request));
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                        } else {
                            showToast("用户名或密码错误");
                            if (failedCount > 3) {
                                failedCount = 0;
                            }
                            failedCount++;
                            setLoginButtonState(failedCount);
                            Log.i("xzx", failedCount + "");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        showToast(context.getString(R.string.error_json_request));
                    }
                }
            }
        });
    }


    public void setProgressVisible(int visibility) {
        iView.showProgress(visibility);
    }

    public void intoNextActivity() {
        iView.intoNextActivity();
    }

    public void setLoginButtonState(int failedCount) {
        iView.setLoginButtonStatus(failedCount);
    }


    public void showToast(String msg) {
        iView.showToast(msg);
    }


}
